package com.ducquoc.examreviewdegreea1;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class DocLoadDataAsyncTask extends AsyncTask<Void, Integer, Void> {
	// Khai bao Activity de luu dia chi cua DocLoadDataActivity
	Activity contextCha;

	// constructor nay duoc truyen vao la DocLoadDataActivity
	public DocLoadDataAsyncTask(Activity ctx) {
		contextCha = ctx;
	}

	// Ham nay se duoc thuc hien dau tien
	@Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub
		super.onPreExecute();
		Toast.makeText(contextCha, "Đang tải dữ liệu!", Toast.LENGTH_LONG)
				.show();
	}

	// Sau do toi ham doInBackground
	// KHONG cap nhat giao dien trong ham nay
	@Override
	protected Void doInBackground(Void... arg0) {
		for (int i = 0; i <= 100; i++) {
			// Nghi 400 milisecond thi tien hanh update UI
			SystemClock.sleep(400);
			// Khi goi ham nay thi onProgressUpdate se thuc thi
			publishProgress(i);
		}
		return null;
	}

	/**
	 * Ta cap nhat giao dien trong ham nay
	 */
	@Override
	protected void onProgressUpdate(Integer... values) {
		// TODO Auto-generated method stub
		super.onProgressUpdate(values);
		// Thong qua contextCha de lay duoc control trong DocLoadDataActivity
		ProgressBar paCha = (ProgressBar) contextCha
				.findViewById(R.id.progressBar1);
		// Vi publishProgress chi truyen 1 doi so
		// nen mang values chi co 1 phan tu
		int giatri = values[0];
		// Tang gia tri cua Progressbar len
		paCha.setProgress(giatri);
		// Dong thoi hien tri gia tri % len TextView
		TextView txtmsg = (TextView) contextCha.findViewById(R.id.textView1);
		txtmsg.setText(giatri + "%");

		Button btnBack = (Button) contextCha.findViewById(R.id.btnBackMain);
		if (giatri == 100) {
			btnBack.setVisibility(View.VISIBLE);
		}
	}

	/**
	 * Sau khi tien trinh thuc hien xong thi ham nay xay ra
	 */
	@Override
	protected void onPostExecute(Void result) {
		// TODO Auto-generated method stub
		super.onPostExecute(result);

	}
}
